#ifndef GB28181_MANAGER_H
#define GB28181_MANAGER_H

#include "gb28181_service.h"
#include "common_config_manager.h"
#include <memory>
#include <string>
#include <vector>
#include <mutex>
#include <nlohmann/json.hpp>

namespace El {
namespace GB28181 {

class GB28181Manager {
public:
    static GB28181Manager &GetInstance();

    bool Initialize();
    void Shutdown();

    bool LoadConfig();
    std::string GetConfig() const;

    bool StartServices();
    void StopServices();
    bool IsServiceRunning(int service_index = -1) const;

    DeviceStatus GetDeviceStatus(int server_index = 0) const;
    std::string GetStatusString(DeviceStatus status) const;

private:
    GB28181Manager() = default;
    ~GB28181Manager() = default;
    GB28181Manager(const GB28181Manager &) = delete;
    GB28181Manager &operator=(const GB28181Manager &) = delete;

    // 配置变更监听相关
    void RegisterConfigListener();
    void UnregisterConfigListener();
    bool OnConfigChanged(const nlohmann::json &config);

    // 服务管理
    bool CreateService(const nlohmann::json &serviceConfig, int index);
    bool NormalizeConfig(const nlohmann::json &config, nlohmann::json &out_servers, bool &enabled) const;

    std::vector<std::shared_ptr<GB28181Service>> services_;
    nlohmann::json current_raw_config_;
    nlohmann::json current_config_;
    bool initialized_ = false;
    int32_t config_listener_id_ = -1; // 配置监听器ID
    bool module_enabled_ = true;
};

} // namespace GB28181
} // namespace El

#endif // GB28181_MANAGER_H
